//
//  SearchTitleViewController.m
//  网络FM
//
//  Created by dlios on 15/6/1.
//  Copyright (c) 2015年 dengzhicheng.com. All rights reserved.
//

#import "SearchTitleViewController.h"
#import "FeelingTableViewCell.h"
#import <AFNetworking.h>
#import "Cover.h"
#import <UIImageView+WebCache.h>
#import "SearchAnchorDetailModel.h"
#import <MJRefresh.h>
#import "PlayerViewController.h"
#import "HistoryModel.h"
#import "HistoryDatabase.h"



@interface SearchTitleViewController ()<UITableViewDataSource,UITableViewDelegate>

@end

@implementation SearchTitleViewController
- (void)dealloc
{
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self  = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
        
        
        
    }
    return self;
}
- (void)loadView
{
    [super loadView];
    [self createTableView];
    [self SearchConnetion];
    
    // 自定义导航栏返回按钮
    UIButton *navButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [navButton addTarget:self action:@selector(navButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateNormal];
    [navButton setImage:[UIImage imageNamed:@"返回.jpg"] forState:UIControlStateHighlighted];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:navButton]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = self.model.name;
    
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



// 导航栏返回按钮点击事件
- (void)navButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)createTableView
{
    self.table = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64) style:UITableViewStylePlain];
    self.table.dataSource = self;
    self.table.rowHeight = self.view.frame.size.width / 4 + 20;
    self.table.delegate = self;
    self.table.separatorStyle = UITableViewCellSelectionStyleNone;
    //上拉刷新下拉加载
    [self.table addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(Refresh)];
    
    [self.view addSubview:self.table];
    self.table.showsVerticalScrollIndicator = NO;
    [self.table release];
}

#pragma mark -
#pragma mark 上拉刷新 下拉加载/Users/dlios/NetWorkFM/网络FM/网络FM.xcodeproj
- (void)Refresh
{
    [self.table reloadData];
    [self.table.header endRefreshing];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cell";
    FeelingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[FeelingTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify];
    }
    SearchAnchorDetailModel *model = [self.array objectAtIndex:indexPath.row];
    NSString *url = [NSString stringWithFormat:@"%@",model.cover];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:[NSString stringWithFormat:@"占位图.jpg"]] options:SDWebImageRetryFailed];
    cell.FMName.text = model.title;
    cell.anchorName.text =  model.speak;
    cell.listen_count.text = [NSString stringWithFormat:@"%ld",(long)model.favnum];
    if (indexPath.row % 2) {
        
        cell.frame = CGRectMake(-320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
        
    }
    else{
        
        cell.frame = CGRectMake(320 ,cell.frame.origin.y ,cell.frame.size.width, cell.frame.size.height);
        
        [UIView animateWithDuration:0.7 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        } completion:^(BOOL finished) {
            ;
        }];
    }
    return cell;
}



//网络请求
- (void)SearchConnetion
{
    //choiceDetailcell的网络请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = [NSString stringWithFormat:@"http://bapi.xinli001.com/fm2/broadcast_list.json/?offset=0&v=1&key=c605710a2343f6da4ac22c8cce194bd0&rows=15&tag="];
    NSString *s = [NSString stringWithFormat:@"%@%@",str,self.model.name];
    
    
    s = [s stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [manager GET:s parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *array = [bigDic objectForKey:@"data"];
        
        for (NSMutableDictionary *dic in array) {
            
            SearchAnchorDetailModel *model = [[SearchAnchorDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];
            
        }
        [self.table reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    }];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [self.table deselectRowAtIndexPath:[self.table indexPathForSelectedRow] animated:YES];
    PlayerViewController *player = [[PlayerViewController alloc]init];
    SearchAnchorDetailModel *model = [self.array objectAtIndex:indexPath.row];
    player.picURL = model.cover;
    player.urlForPlay = model.url;
    
    HistoryModel *history = [[HistoryModel alloc]init];
    history.titleName = model.title;
    history.imageName = model.cover;
    history.videoUrl = model.url;
    history.people = model.speak;
    [HistoryDatabase insertWithModel:history];
    
    player.picURL = model.absolute_url;
    player.urlForPlay = model.url;
    player.picURL = model.cover;
    player.tit = model.title;
    player.speaker = model.speak;
    
    UIView *controlView = [self.view.window.subviews objectAtIndex:1];
    [controlView setAlpha:0];
    
    [self.navigationController pushViewController:player animated:YES];
    
}


@end
